package com.kandroid.chatclient;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kandroid.chatclient.bean.ChatRespBean;
import com.kandroid.chatclient.bean.MsgBean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @BindView(R.id.et_chat_input)
    EditText inputEt;
    @BindView(R.id.tv_send_msg)
    TextView sendTv;
    @BindView(R.id.lv_chat_msg)
    ListView chatLv;
    @BindView(R.id.tv_settings)
    TextView settingsTv;

    private OkHttpClient mOkHttpClient;
    private Gson mGson = new Gson();

    private List<MsgBean> chatRecord = new ArrayList<>(); //聊天记录

    private ChatListAdapter adapter;
    private String avatarPath;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();
        ButterKnife.bind(this);

        adapter = new ChatListAdapter(chatRecord);
        initViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
        sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        avatarPath = sharedPreferences.getString("avatar", "");
        adapter.notifyDataSetChanged();
    }

    private void initViews() {
        sendTv.setOnClickListener(this);
        settingsTv.setOnClickListener(this);
        inputEt.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (KeyEvent.KEYCODE_ENTER == keyCode && KeyEvent.ACTION_DOWN == event.getAction()) {
                    String message = inputEt.getText().toString().trim();
                    if (!TextUtils.isEmpty(message)) {
                        sendMsg(message);
                    }
                    return true;
                }
                return false;
            }
        });

        chatLv.setAdapter(adapter);
    }

    private void sendMsg(String message) {
        chatRecord.add(new MsgBean(0, message));
        adapter.notifyDataSetChanged();
        inputEt.setText("");
        chatLv.setSelection(adapter.getCount() - 1);
        sendChat(message);
    }

    private void sendChat(final String message) {
        mOkHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(String.format("http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s", message))
                .method("GET", null)
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String content = response.body().string();
                ChatRespBean replyBean = mGson.fromJson(content, ChatRespBean.class);
                final String reply = replyBean.getContent();

                sleep(1500);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        chatRecord.add(new MsgBean(1, reply));
                        adapter.notifyDataSetChanged();
                        chatLv.setSelection(adapter.getCount() - 1);
                    }
                });
            }
        });
    }

    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_send_msg: {
                String message = inputEt.getText().toString().trim();
                if (!TextUtils.isEmpty(message)) {
                    sendMsg(message);
                }
                break;
            }
            case R.id.tv_settings: {
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                break;

            }
        }
    }

    class ChatListAdapter extends BaseAdapter {
        private List<MsgBean> mData;

        public ChatListAdapter(List<MsgBean> data) {
            this.mData = data;
        }

        @Override
        public int getCount() {
            return mData != null ? mData.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MsgBean msgBean = mData.get(position);
            if (convertView == null) {
                if (getItemViewType(position) == 0) {
                    convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.listitem_chat_message, null);
                } else {
                    convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.listitem_chat_message_right, null);
                }
            }

            TextView messageTv = convertView.findViewById(R.id.tv_message);
            ImageView avatarIv = convertView.findViewById(R.id.iv_avatar);

            messageTv.setText(msgBean.getMessage());
            if (!TextUtils.isEmpty(avatarPath)
                    && msgBean.getUserId() == 0) {
                Bitmap bitmap = BitmapFactory.decodeFile(avatarPath);
                if (bitmap != null) {
                    avatarIv.setImageBitmap(bitmap);
                }
            }
            return convertView;
        }

        @Override
        public int getItemViewType(int position) {
            return mData.get(position).getUserId();
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }
    }
}
